
const Service = require('egg').Service;

class ExpertFollowService extends Service {


  async getFollowListByQuery(query, option) {
    let expertFollows = await this.ctx.model.ExpertFollow.find(
      query,
      [],
      option
    ).lean();

    const totalCount = await this.ctx.model.ExpertFollow.count(query).exec() || 0;

    if (expertFollows.length === 0) {
      return [];
    }

    await Promise.all(
      expertFollows.map(async (item) => {
        const [ expert ] = await this.ctx.service.expert.getLightExpertDetail({
          expertId: item.expert_id,
        });
        item.name = expert.name;
        item.shanchang = expert.shanchang;
        item.physician = expert.physician;
        item.categray = expert.categray;
        item.avatar_image = expert.avatar_image;
        return item;
      })
    )


    return [ expertFollows, totalCount ];

  }

  async postExertFollow({
    expertId,
    userId,
  }) {
    const ctx = this.ctx;

    const query = { expert_id: expertId, user_id: userId };

    const resultData = await this.ctx.model.ExpertFollow.findOne(query);

    const updateCount = async function() {
      const c = await ctx.model.ExpertFollow.count({ expert_id: expertId, follow: true });
      await ctx.model.Expert.update({ _id: expertId }, { follow_total_count: c });
    }

    if (!resultData) {
      const follow = new this.ctx.model.ExpertFollow();
      follow.expert_id = expertId;
      follow.user_id = userId;
      follow.update_at = new Date();
      follow.follow = true;
      await follow.save();
      await updateCount();
      return
    }
    
    const update = await this.ctx.model.ExpertFollow.findOneAndUpdate(
      query,
      {
        follow: true,
        update_at: new Date()
      }
    );
    await updateCount();
    
    return [ update ];
  }

  async cancelExpertFollow({
    expertId,
    userId,
  }) {
    const ctx = this.ctx;
    const query = { expert_id: expertId, user_id: userId };

    const resultData = await this.ctx.model.ExpertFollow.findOne(query);

    const updateCount = async function() {
      const c = await ctx.model.ExpertFollow.count({ expert_id: expertId, follow: true });
      const resc = await ctx.model.Expert.update({ _id: expertId }, { follow_total_count: c });
    }

    if (resultData) {
      const update = await this.ctx.model.ExpertFollow.findOneAndUpdate(
        query,
        {
          follow: false,
          update_at: new Date(),
        }
      );
      await updateCount();
      return [ update ];
    }

    return [];
  }
}

module.exports = ExpertFollowService;
